import io
import os
import re

import time
import traceback

from PIL import Image
from PIL.ExifTags import TAGS

from xjlibrary.py2py3 import PY2
from xjlibrary.py2py3._mycompat import text_type
from xjlibrary.tools.base_utils import __os_sep__, _windows_device_files, deprecated


@deprecated
def newTitle(title):
    """
    替换掉标题里的特殊符号 方便保存
    :param title: 
    :return: 
    """
    err_str = r"[\/\\\:\*\?\"\<\>\|]"
    new_title = re.sub(err_str, "_", title)
    return new_title

@deprecated
def get_file_name(filename):
    """
    得到文件名  去掉路径
    :param filename: 
    :return: 
    """
    return filename.split(__os_sep__)[-1]
@deprecated
def get_filename_not_extsep(filename):
    """
    获取文件名  去除后缀和路径
    :param filename:
    :return:
    """
    filename = get_file_name(filename)
    return os.extsep.join(filename.split(os.extsep)[:-1])

@deprecated
def parallelIterations(lista, listb):
    """
    并行迭代 会迭代出最少的那个  如下面的f被丢弃
        if (lista is None and listb is None):
        lista = ['1', '2', '3', '4', '5']
        listb = ['a', 'b', 'c', 'd', 'e', 'f']
    :param lista: 
    :param listb: 
    :return: 
    """
    for aa, bb in zip(lista, listb):
        yield aa, bb

@deprecated
def list_to_string(mlist):
    """
     b = ['a', 'b', 'c', 'd', 'e', 'f']
    :param mlist: 
    :return:  string abcdef
    """
    return "".join(mlist)

@deprecated
def string_to_list(string):
    """
    string 转换成list
    :param string: 
    :return:  一个list每个元素一个char
    """
    mlist = [string[x] for x in range(len(string))]
    return mlist

@deprecated
def filter_string_blank_space(filterobj):
    """
    过滤字符串空格
    例如  list = [' n 1 2', ' c 4s r   ']
    :return ['n12', 'c4sr']
    
    """
    if isinstance(filterobj, str):
        return "".join(filterobj.split())
    if isinstance(filterobj, list):
        listobj = ["".join(x.split()) for x in filterobj]
        return listobj
    else:
        assert "not have this Type，please check parameter Type" + __file__

@deprecated
def get_file_ext_name(filename, double_ext=True):
    """
    获取文件后缀
    os.extsep = "."
    :param filename: 传入文件名或者带路径的文件
    :param double_ext: 
    :return: 
    """
    li = filename.split(os.extsep)  # 以.分割
    if len(li) <= 1:  # 如果分割后只有一个  那么这没有文件后缀
        return ''
    else:
        if li[-1].find(__os_sep__) != -1:  # 如果在最后一个中发现分割符 也没有后缀
            return ''
    if double_ext:
        if len(li) > 2:  # 有可能后缀有多个组成 这里我们最多返回两个字符串以点链接形成的后缀
            if li[-2].find(__os_sep__) == -1:
                return '%s.%s' % (li[-2], li[-1])
    return li[-1]

@deprecated
def is_img(ext):
    """
    传入后缀
    判断是不是图片文件 后期加入更多文件后缀
    :param ext: 
    :return: 
    """
    ext = ext.lower()
    if ext == '.jpg':
        return True
    elif ext == '.png':
        return True
    elif ext == '.jpeg':
        return True
    elif ext == '.bmp':
        return True
    else:
        return False

@deprecated
def getDirAllFiles(path):
    """
    返回所有的文件 不会返回目录 目的是得到一个文件列表
    :param path:  给定一个路径 如 C:/Users/XD/Pictures/所有视频/
    :return: 
    """
    # 遍历子目录
    for path, dirNames, fileNames in os.walk(path):
        # 获取当前目录的所有文件
        for fileName in fileNames:
            yield os.path.join(path, fileName)


@deprecated
def secure_filename(filename):
    r"""Pass it a filename and it will return a secure version of it.  This
    filename can then safely be stored on a regular file system and passed
    to :func:`os.path.join`.  The filename returned is an ASCII only string
    for maximum portability.

    On windows systems the function also makes sure that the file is not
    named after one of the special device files.
    
    经我改变 支持中文

    >>> secure_filename("My cool movie.mov")
    'My_cool_movie.mov'
    >>> secure_filename("../../../etc/passwd")
    'etc_passwd'
    >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
    'i_contain_cool_umlauts.txt'

    The function might return an empty filename.  It's your responsibility
    to ensure that the filename is unique and that you generate random
    filename if the function returned an empty one.

    .. versionadded:: 0.5

    :param filename: the filename to secure
    """
    if isinstance(filename, text_type):
        # 此模块提供对Unicode字符数据库的访问，该字符数据库为所有Unicode字符定义字符属性。该数据库中的数据基于UnicodeData.txt
        # 可从ftp://ftp.unicode.org/公开获得的文件版本5.2.0 。
        from unicodedata import normalize
        # ignore参数会忽略无法编码的字符
        # normalize 为标准化底层编码 http://python3-cookbook.readthedocs.io/zh_CN/latest/c02/p09_normalize_unicode_text_to_regexp.html
        filename = normalize('NFKD', filename).encode('utf-8')
        if not PY2:
            filename = filename.decode('utf-8')
    for sep in os.path.sep, os.path.altsep:
        if sep:
            # 替换用后面的替换前面的
            filename = filename.replace(sep, ' ')
    filename = str(re.sub(':', '', '_'.join(
        filename.split()))).strip('._')

    # on nt a couple of special files are present in each folder.  We
    # have to ensure that the target file is not such a filename.  In
    # this case we prepend an underline
    if os.name == 'nt' and filename and \
            filename.split('.')[0].upper() in _windows_device_files:
        filename = '_' + filename

    return filename

@deprecated
def gettime(filename):
    """
    获取文件时间，这个是获取文件的属性，不利于获取创造时间 因为每一次更改时间都会更新
    :param filename: 
    :return: 
    """
    ModifiedTime = time.localtime(os.stat(filename).st_mtime)  # 文件访问时间
    y = time.strftime('%Y', ModifiedTime)
    m = time.strftime('%m', ModifiedTime)
    d = time.strftime('%d', ModifiedTime)
    H = time.strftime('%H', ModifiedTime)
    M = time.strftime('%M', ModifiedTime)
    import datetime
    d2 = datetime.datetime(int(y), int(m), int(d), int(H), int(M))
    return d2

@deprecated
def get_image_filename_time(filename):
    # 这是从文件名中获取时间  主要用于手机图片的命名格式有效
    li = filename.split(__os_sep__)
    if li[-1].find(__os_sep__) != -1:
        return ''
    if li[-1].find(os.extsep) != -1:
        li2 = li[-1].split(os.extsep)
        li3 = li2[-2].split("_")
        if len(li3) == 1:
            return li3[0]
        return li3[-2] + li3[-1]
    return ''

@deprecated
def get_exif_data(fname):
    """Get embedded EXIF data from image file.
    获取文件中隐藏的信息
    """
    from PIL import Image
    ret = {}
    try:
        img = Image.open(fname)
        if hasattr(img, '_getexif'):
            exifinfo = img._getexif()
            if exifinfo is not None:
                for tag, value in exifinfo.items():
                    decoded = TAGS.get(tag, tag)
                    ret[decoded] = value
    except IOError:
        print('IOERROR ' + fname)
    return ret

@deprecated
def Img2Jpg(buf, dstFile):
    """
    vip 图片标准程序
    :param buf:
    :param dstFile:
    :return:
    """
    print('Img2Jpg %s ...' % dstFile)

    exMsg = ''
    try:
        srcImg = Image.open(io.BytesIO(buf))
        dstImg = srcImg.resize((108, 150), Image.ANTIALIAS).convert('RGB')
        dstImg.save(dstFile, 'JPEG')
    except:
        exMsg = '* %s' % traceback.format_exc()
        print(exMsg)
    if exMsg:
        return False

    return True
